<template>
  <div class="component simple_table">
    <el-table v-loading="loading" ref="_simpleTable" v-bind="proxy.$attrs" :data="_data" stripe style="width: 100%">
      <slot name="-"></slot>
      <slot name="empty"></slot>
      <template v-if="_configs && _configs.length">
        <el-table-column v-for="(c, i) in _configs" :key="i" v-bind="c" />
      </template>
      <slot name="opt"></slot>
    </el-table>
  </div>
  <div class="component simple_table_pagination" v-if="_pageable">
    <el-pagination background :layout="pageLayout" :page-sizes="pageSizes" :total="_total" v-model:current-page="pageNum" v-model:page-size="pageSize" />
  </div>
</template>

<script lang="ts" setup>
interface Props {
  _configs: Array<{ prop: string, label: string, formatter?: Function, width?: number }>
  _data: Array<object>
  _lazy?: boolean
  _pageable?: boolean
  _total?: number
}

const props = withDefaults(defineProps<Props>(), {
  _configs: () => [],
  _data: () => [],
  _lazy: false,
  _pageable: true,
  _total: 0
})

// const props = withDefaults(defineProps<{
//   _configs: Array<{ prop: string, label: string, formatter?: Function, width?: number }>
//   _data: Array<object>
//   _lazy?: boolean
//   _pageable?: boolean
//   _total?: number
// }>(), {
//   _pageable: true,
//   _lazy: false,
//   _configs: () => [],
//   _data: () => [],
//   _total: 0
// })

const emits = defineEmits<{ (e: '_load', pageNum: number, pageSize: number): void }>()

const pageLayout = ['sizes', 'prev', 'pager', 'next'].join(',')
const pageSizes = [10, 20, 50]

let pageNum = ref(1)
let pageSize = ref(10)
let loading = ref(true)

const _init = () => {
  pageNum.value = 1
  _load()
}

const _load = () => {
  loading.value = true
  emits('_load', pageNum.value, pageSize.value)
  loading.value = false
}

defineExpose({
  _init,
  _load
})

watch(() => pageNum.value, (n, o) => {
  if (n) _load()
}, { immediate: false })

watch(() => pageSize.value, (n, o) => {
  if (n) _load()
}, { immediate: false })

const _simpleTable = ref()
const { proxy }: any = getCurrentInstance()

onMounted(() => {
  const { _lazy } = toRefs<Props>(props)
  // for (const [key, value] of Object.entries(_simpleTable.value)) {
  //   if (key) proxy[key] = value
  // }
  if (!_lazy?.value) _init()
  else loading.value = false
})
</script>

<style lang="less" scoped>
.simple_table {
  width: 100%;
  height: auto;
  min-height: 600px;
  padding: 10px 5px;
  :deep(.el-scrollbar__view) {
    width: 100%;
  }
}
.simple_table_pagination {
  width: 100%;
  padding: 40px 0 20px 0;
  .el-pagination {
    text-align: center;
    justify-content: center;
  }
}
</style>
